package controllers

import (
	"classmates/models"
	"strings"
	"time"

	"github.com/beego/beego/v2/server/web/context"
	"github.com/dgrijalva/jwt-go"
)

const (
	//CurrentStudent 当前登录的学员
	CurrentStudent = "currentstudent"
	//CurrentManager 当前登录的管理员
	CurrentManager = "currentmanager"
	//AccessLabel 当前api调用者的redis key
	AccessLabel = "accessLabel"
)

// FilterUser 过滤钩子
func FilterUser(ctx *context.Context) {
	if strings.Index(ctx.Request.URL.Path, "/api/classmates/login") == 0 {
		return
	}
	if strings.Index(ctx.Request.URL.Path, "/api/records/loadPersons") == 0 {
		return
	}
	if strings.Index(ctx.Request.URL.Path, "/api/records/clearChoujiang") == 0 {
		return
	}
	var authString = ctx.Request.FormValue("token")
	if ctx.Input.Header("token") != "" {
		authString = ctx.Input.Header("token")
	}
	result := make(map[string]interface{})
	token := new(jwt.Token)
	token.Valid = false
	var err error
	if authString != "" {
		token, err = jwt.Parse(authString, func(token *jwt.Token) (interface{}, error) {
			return []byte(models.JwtString), nil
		})
		if err != nil {
			result["code"] = 401
			result["data"] = "请重新登录"
			ctx.Output.JSON(result, false, false)
			return
		}

	}

	if token.Valid {
		userinfo, ok := token.Claims.(jwt.MapClaims)
		if ok == false {
			result["code"] = 401
			result["data"] = "token无效"

			ctx.Output.JSON(result, false, false)
			return
		}
		if userinfo["id"] == nil || userinfo["id"] == "" {
			result["code"] = 400
			result["data"] = "token无效"
			ctx.Output.JSON(result, false, false)
			return
		}

		expireTime := userinfo["exp"].(float64)

		if int(expireTime) <= int(time.Now().Unix()) {
			result["code"] = 400
			result["data"] = "登陆已经过期"
			ctx.Output.JSON(result, false, false)
			return
		}
		ctx.Input.SetData("id", userinfo["id"].(float64))
		ctx.Input.SetData("sn", userinfo["sn"].(string))
	} else {
		result["code"] = 400
		result["data"] = "请先登录"
		ctx.Output.JSON(result, false, false)
	}

}

// GetJwtString GetJwtString
func GetJwtString(expire int, id interface{}, sn string) (string, error) {
	token := jwt.New(jwt.SigningMethodHS256)
	claims := make(jwt.MapClaims)
	now := time.Now()
	claims["exp"] = now.Add(time.Hour * time.Duration(expire)).Unix()
	claims["iat"] = now.Unix()
	claims["id"] = id
	claims["sn"] = sn // 0是学员，1 是管理员.2是校区工作员
	token.Claims = claims
	tokenString, err := token.SignedString([]byte(models.JwtString))
	return tokenString, err
}
